import requests
from django.conf import settings
import logging

logger = logging.getLogger(__name__)

def get_wx_access_token(code):
    """
    获取微信小程序的access_token和openid
    """
    try:
        url = 'https://api.weixin.qq.com/sns/jscode2session'
        params = {
            'appid': settings.WX_APP_ID,
            'secret': settings.WX_APP_SECRET,
            'js_code': code,
            'grant_type': 'authorization_code'
        }
        
        logger.info(f"Requesting WeChat API with params: {params}")
        response = requests.get(url, params=params)
        logger.info(f"WeChat API response: {response.text}")
        
        data = response.json()
        
        if 'errcode' in data:
            logger.error(f"WeChat API error: {data}")
            return data
            
        return {
            'openid': data.get('openid'),
            'session_key': data.get('session_key')
        }
    except Exception as e:
        logger.error(f"Error in get_wx_access_token: {str(e)}")
        return {
            'errcode': -1,
            'errmsg': str(e)
        } 